{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "#载入数据集\n",
    "mnist = input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n",
    "\n",
    "#每个批次的大小\n",
    "batch_size = 100\n",
    "#计算一共有多少个批次\n",
    "n_batch = mnist.train.num_examples // batch_size\n",
    "\n",
    "#定义两个placeholder\n",
    "x = tf.placeholder(tf.float32,[None,784])\n",
    "y = tf.placeholder(tf.float32,[None,10])\n",
    "\n",
    "#创建一个简单的神经网络\n",
    "W = tf.Variable(tf.zeros([784,10]))\n",
    "b = tf.Variable(tf.zeros([10]))\n",
    "prediction = tf.nn.softmax(tf.matmul(x,W)+b)\n",
    "\n",
    "#二次代价函数\n",
    "# loss = tf.reduce_mean(tf.square(y-prediction))\n",
    "loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\n",
    "#使用梯度下降法\n",
    "train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)\n",
    "\n",
    "#初始化变量\n",
    "init = tf.global_variables_initializer()\n",
    "\n",
    "#结果存放在一个布尔型列表中\n",
    "correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置\n",
    "#求准确率\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    for epoch in range(21):\n",
    "        for batch in range(n_batch):\n",
    "            batch_xs,batch_ys =  mnist.train.next_batch(batch_size)\n",
    "            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})\n",
    "        \n",
    "        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})\n",
    "        print(\"Iter \" + str(epoch) + \",Testing Accuracy \" + str(acc))"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
